package org.log4jeditor.xml.editor;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;

public class IOUtils {

	public static void copyDir(File src, File target) throws Exception {
		if (!target.exists()) {
			target.mkdir();
		}
		File[] files = src.listFiles();
		for (File file : files) {
			if(file.getName().charAt(0) == '.') {
				//skip hidden files and directories
				continue;
			}
			File toFile = new File(target, file.getName());
			if (file.isDirectory()) {
				copyDir(file, toFile);
			} else {
				copyFile(file, toFile);
			}
		}
	}

	public static void copyFile(File src, File target) throws Exception {
		BufferedOutputStream bos = null;
		BufferedInputStream bis = null;
		try {
			bos = new BufferedOutputStream(new FileOutputStream(target));
			bis = new BufferedInputStream(new FileInputStream(src));
			while (bis.available() > 0) {
				int size = bis.available();
				if (size > 1024)
					size = 1024;
				byte[] b = new byte[size];
				bis.read(b, 0, b.length);
				bos.write(b);
			}
		} finally {
			bis.close();
			bos.close();
		}
	}
}
